package com.wanghang.springcloud.mcp.mcp.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wanghang.springcloud.mcp.mcp.bean.McpResponse;
import com.wanghang.springcloud.mcp.mcp.bean.McpTool;
import com.wanghang.springcloud.mcp.mcp.service.McpClient;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 基于HTTP的MCP客户端实现
 *
 */
@Slf4j
@RequiredArgsConstructor
public class HttpMcpClient implements McpClient {

    private final RestTemplate restTemplate;


    private final ObjectMapper objectMapper;


    private final String baseUrl;



    private final String serviceName;



    @Override
    public McpResponse callTool(String toolName, Map<String, Object> arguments) throws Exception {
        log.info("调用MCP服务[{}]工具: {}, 参数: {}", serviceName, toolName, arguments);
        // 构建请求体
        Map<String, Object> request = new HashMap<>();
        request.put("method", "tools/call");
        request.put("params", Map.of(
                "name", toolName,
                "arguments", arguments != null ? arguments : new HashMap<>()
        ));

        // 发送HTTP请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(baseUrl + "/mcp", entity, String.class);
        if (response.getStatusCode().is2xxSuccessful()) {
            Object data = objectMapper.readValue(response.getBody(), Object.class);
            log.info("MCP服务[{}]调用成功", serviceName);
            return McpResponse.success(data);
        } else {
            log.error("MCP服务[{}]调用失败: {}", serviceName, response.getStatusCode());
            return McpResponse.error("HTTP错误: " + response.getStatusCode());
        }
    }





    @Override
    public List<McpTool> listTools() throws Exception {
        log.info("获取MCP服务[{}]工具列表", serviceName);

        Map<String, Object> request = new HashMap<>();
        request.put("method", "tools/list");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(baseUrl + "/mcp", entity, String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            TypeReference<List<McpTool>> typeRef = new TypeReference<List<McpTool>>() {};
            List<McpTool> tools = objectMapper.readValue(response.getBody(), typeRef);
            log.info("获取到MCP服务[{}]工具数量: {}", serviceName, tools.size());
            return tools;
        } else {
            log.error("获取MCP服务[{}]工具列表失败: {}", serviceName, response.getStatusCode());
            return List.of();
        }
    }
}
